﻿using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using TmU220PrintHelperV2d0.Entity;
using TmU220PrintHelperV2d0.Singleton;
using ZhangLogSysV1d0;
using System.Xml;
using XpQ200PrintHelperV2d0;
using TmU220PrintHelperV2d0.Interface;

namespace TmU220PrintHelperV2d0.Service
{
    /// <summary>
    /// 打印机监视线程
    /// 打印机状态：是否连接，是否可用，是否缺纸，卷纸盖是否正常，打印机是否忙
    /// </summary>
    public class ThreadPrinterMonitorV2d0
    {
        #region 控制属性
        public string PrinterName { get; set; }
        /// <summary>
        /// 打印机ip
        /// </summary>
        public string PrinterIp { get; set; }
        /// <summary>
        /// 打印机端口
        /// </summary>
        public int PrinterPort { get; set; }
        /// <summary>
        /// 常驻汉字字库编码
        /// </summary>
        public string FontLibraryEncodingName { get; set; }
        /// <summary>
        /// 是否繁体
        /// </summary>
        public bool IsTraditional { get; set; }
        /// <summary>
        /// 连接打印机套接字
        /// </summary>
        public TcpClient PrinterTcpClient = null;
        /// <summary>
        /// 心跳检查信号量
        /// </summary>
        public ManualResetEvent PulseCheckMRE = new ManualResetEvent(false);
        /// <summary>
        /// 套接字连接的超时时间
        /// </summary>
        int SocketConnectTimerOutMilliSecond { get; set; }
        /// <summary>
        /// 接收到的字符串
        /// </summary>
        public StringBuilder ReceiveSBuilder = new StringBuilder();

        //打印任务的数据队列
        public ConcurrentQueue<PrintTaskV2d0> PrintTaskQueue;
        /// <summary>
        /// 最后一次完成打印任务的时间
        /// </summary>
        public DateTime LastPrintCompleteTime { get; set; }
        /// <summary>
        /// 设备类型 TM-U220,XP-Q200
        /// </summary>
        public string DeviceType { get; set; }

        
        #endregion 控制属性
        #region 打印机状态 
        
        private bool _IsConnected;
        /// <summary>
        /// 是否已与打印机连接
        /// </summary>
        public bool IsConnected
        {
            get
            {
                lock (LockIsConnected)
                {
                    return _IsConnected;
                }
            }
            set
            {
                lock (LockIsConnected)
                {
                    _IsConnected = value;
                }
            }
        }
        private object LockIsConnected = new object();

        private bool _IsPrinterReady;
        /// <summary>
        /// 打印机是否可用
        /// </summary>
        public bool IsPrinterReady
        {
            get
            {
                lock (LockIsPrinterReady)
                {
                    return _IsPrinterReady;
                }
            }
            set
            {
                lock (LockIsPrinterReady)
                {
                    _IsPrinterReady = value;
                }
            }
        }
        private object LockIsPrinterReady = new object();

        private bool _IsPaperExhausted;
        /// <summary>
        /// 是否缺纸
        /// </summary>
        public bool IsPaperExhausted
        {
            get
            {
                lock (LockIsPrinterReady)
                {
                    return _IsPaperExhausted;
                }
            }
            set
            {
                lock (LockIsPrinterReady)
                {
                    _IsPaperExhausted = value;
                }
            }
        }
        private object LockIsPaperExhausted = new object();

        private bool _IsJzgStatusNormal;
        /// <summary>
        /// 卷纸盖状态是否正常 关闭为正常，打开为异常
        /// </summary>
        public bool IsJzgNormal
        {
            get
            {
                lock (LockIsPrinterReady)
                {
                    return _IsJzgStatusNormal;
                }
            }
            set
            {
                lock (LockIsPrinterReady)
                {
                    _IsJzgStatusNormal = value;
                }
            }
        }
        private object LockIsJzgStatusNormal = new object();
        
        private bool _IsBusy;
        /// <summary>
        /// 打印机忙
        /// </summary>
        public bool IsBusy
        {
            get
            {
                lock (LockIsBusy)
                {
                    return _IsBusy;
                }
            }
            set
            {
                lock (LockIsBusy)
                {
                    _IsBusy = value;
                }
            }
        }
        private object LockIsBusy = new object();
        /// <summary>
        /// 打印速度，每行用时，单位秒
        /// </summary>
        public Double BasePrintSpeed = 2.2;
        #endregion
        #region 事件相关
        /// <summary>
        /// 打印机工作状态
        /// </summary>
        public event EventHandler<PrinterStatusV2d0> PrinterStatusEvent = null;
        /// <summary>
        /// 打印任务完成事件
        /// </summary>
        public event EventHandler<PrintTaskV2d0> PrintCompleteEvent = null;
        /// <summary>
        /// 打印任务错误事件
        /// </summary>
        public event EventHandler<PrintTaskV2d0> PrintErrorEvent = null;
        #endregion 事件相关
        #region 线程相关
        public bool Running = false;
        /// <summary>
        /// epc扫描线程
        /// </summary>
        private Thread Thread_main = null;
        /// <summary>
        /// 线程序号
        /// </summary>
        public int Thread_index = 0;
        //循环次数
        public int CycleCount = 0;
        public int CycleCountOfIsNotReady = 0;
        /// <summary>
        /// 打印任务执行日志
        /// </summary>
        public PrintLogV3d0 PrintLog { get; set; }
        /// <summary>
        /// 启动线程
        /// </summary>
        public void StartThread()
        {
            this.Thread_main = new Thread(new System.Threading.ThreadStart(this.ThreadStart));
            this.Running = true;
            LastPrintCompleteTime = DateTime.Now;
            //作为后台线程
            this.Thread_main.IsBackground = true;
            //启动线程
            this.Thread_main.Start();
        }
        /// <summary>
        /// 停止线程
        /// </summary>
        public void StopThread()
        {
            this.Running = false;
            if (PrinterTcpClient != null) PrinterTcpClient.Close();
            if (Thread_main != null) Thread_main.Abort();
        }
        /// <summary>
        /// 发布连接失败的打印机状态事件
        /// </summary>
        public void PublishPrinterStatusEventOfConnectFailed()
        {
            IsConnected = false;//重新初始化
            IsPrinterReady = false;
            IsBusy = false;
            PrinterTcpClient.Close();
            //发布打印机状态事件
            //SimpleLoger.Instance.Info("已连接，但未收到打印机发出的指令");
            if (PrinterStatusEvent != null)
                PrinterStatusEvent(this, new PrinterStatusV2d0(IsConnected, IsPrinterReady, IsBusy, IsJzgNormal));

        }
        /// <summary>
        /// 线程启动
        /// </summary>
        private void ThreadStart()
        {
            while (Running)
            {
                try
                {
                    if ((PrinterTcpClient == null || (!IsConnected)) || (PrinterTcpClient != null && (!PrinterTcpClient.Connected)))
                    {
                        PulseCheckMRE.Reset();//重置信号为无信号状态，关门，等待开门信号
                        if (!IsConnected)
                        {
                            IsConnected = ConnectToPrinterAndTryInit(PrinterIp, PrinterPort);
                            if (IsConnected)
                            {
                                //若连接正常，会收到打印机发回数据,若超时，则未连接到打印机，发布打印机状态
                                int secondsOfTimeout = 3;//超时时间
                                bool signArrived = PulseCheckMRE.WaitOne(secondsOfTimeout*1000, false);
                                if (!signArrived)   PublishPrinterStatusEventOfConnectFailed();
                            }
                            else PublishPrinterStatusEventOfConnectFailed();                           
                        }                                               
                    }
                    if (IsConnected)
                    {
                        //若打开进纸盒盖时间过长，打印机会自动关闭套接字连接，所以需要进行重连
                        if (!IsPrinterReady)
                        {
                            CycleCountOfIsNotReady++;
                            //重新连接的等待周期
                            int waitCountOfReConnect = 30;
                            if (CycleCountOfIsNotReady > waitCountOfReConnect)
                            {
                                IsConnected = false;
                                CycleCountOfIsNotReady = 0;
                            }
                        }
                        //只有在打印机运行正常，并且打印机未进行打印时，才能进行心跳检测,每超过5次循环做一个心跳检测                       
                        if (IsPrinterReady && (!IsBusy)&&CycleCount>5)
                        {
                            //进行一次心跳检测，并更新打印机状态
                            IsConnected = PrinterPulseCheck();
                            CycleCount = 0;
                        }
                        if (IsConnected && IsPrinterReady && (!IsBusy))
                        {
                            //从数据队列中取一个任务,作为当前打印任务(当前打印任务的文字编码有可能与打印机字库编码不一致)
                            var currentPrintTask = GetPrintTaskFromDataQueue();
                            if(currentPrintTask==null)
                            {
                                //在任务队列无任务时，若最后一次打印的时间距当前时刻超过30分钟，则重新断开再连接一次
                                TimeSpan minutesFromLastPrintComplete = DateTime.Now - LastPrintCompleteTime;
                                if ((minutesFromLastPrintComplete.TotalMinutes > 30) && (PrinterTcpClient != null))
                                {
                                    PrinterTcpClient.Close();
                                    LastPrintCompleteTime = DateTime.Now;
                                }
                            }
                            else if (currentPrintTask != null)
                            {
                                PrintLog = new PrintLogV3d0(currentPrintTask);
                                PrintLog.PrintProcessDescriptionList.Add("装载打印任务:"+ DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                                //任务队列有任务是，执行打印的次数增加1（无论是否打印成功）
                                currentPrintTask.CountOfSendingToPrinter++;
                                //做一个深度复制,需要进行编码转换
                                var currentPrintTaskUsing = HotchPotchV2d0.Clone<PrintTaskV2d0>(currentPrintTask);
                                IsBusy = true;
                                //文字编码转换，big5，gb18030互转
                                SimplifiedAndTraditionalProcess(ref currentPrintTaskUsing, IsTraditional);
                                //发送打印任务
                                SendPrintTaskToPrinter(currentPrintTaskUsing);
                                //PrintLog.PrintProcessDescriptionList.Add("发送打印任务到打印机");
                                int timeOutSecond = (int)(currentPrintTaskUsing.PrintTaskItemList.Count * BasePrintSpeed);
                                //等待开门信号或者超时
                                if (PulseCheckMRE.WaitOne(timeOutSecond * 1000, false))
                                {
                                    //解决卷纸盖打开的问题
                                    if (IsPrinterReady)
                                    {
                                        //该任务打印完成
                                        LastPrintCompleteTime = DateTime.Now;
                                        //发布事件
                                        // 更新act_printer,printtime
                                        currentPrintTask.DataOfPrintTask.act_printer = PrinterName;
                                        currentPrintTask.DataOfPrintTask.printtime = DateTime.Now;
                                        if (PrintCompleteEvent != null)  PrintCompleteEvent(this, currentPrintTask); 
                                        //设置日志属性
                                        PrintLog.PrintProcessDescriptionList.Add("打印完成:"+DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                                        PrintLog.printtime = DateTime.Now;
                                        PrintLog.status = 1;
                                        PrintLog.act_printer = PrinterName;
                                        //写入日志数据表
                                        rms_order_print_log print_log = new rms_order_print_log(PrintLog);
                                        SetDataNetSingletonV1d0.Instance.Run<rms_order_print_log>(print_log);
                                        //HotchPotchV2d0.InsertSinglePrintLogToTable(PrintLog);
                                        //IsPrinterReady = true;
                                        IsBusy = false;
                                    }
                                    else
                                    {
                                        //若在此期间，打印机卷纸盖被打开，则打印任务未完成
                                        //IsConnected = false;
                                        //IsPrinterReady = false;
                                        IsBusy = false;
                                        //发布打印机状态事件
                                        if (PrinterStatusEvent != null)
                                            PrinterStatusEvent(this, new PrinterStatusV2d0(IsConnected, IsPrinterReady, IsBusy, IsJzgNormal));
                                        if (PrintErrorEvent != null)
                                            PrintErrorEvent(this, currentPrintTask);
                                        PrintLog.PrintProcessDescriptionList.Add("卷纸盖打开打印任务中断:"+DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                                        PrintLog.printtime = DateTime.Now;
                                        PrintLog.status = 2;
                                        HotchPotchV2d0.InsertSinglePrintLogToTable(PrintLog);
                                    }
                                }
                                else
                                {
                                    //若超时，则打印任务未完成
                                    if (PrintErrorEvent != null)
                                        PrintErrorEvent(this, currentPrintTask);
                                    //打印机未就绪
                                    IsConnected = false;
                                    IsPrinterReady = false;
                                    IsBusy = false;
                                    //发布打印机状态事件
                                    if (PrinterStatusEvent != null)
                                        PrinterStatusEvent(this, new PrinterStatusV2d0(IsConnected, IsPrinterReady, IsBusy, IsJzgNormal));
                                    PrintLog.PrintProcessDescriptionList.Add("打印超时打印任务未完成" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                                    PrintLog.printtime = DateTime.Now;
                                    PrintLog.status = 2;
                                    HotchPotchV2d0.InsertSinglePrintLogToTable(PrintLog);
                                }
                            }
                        }
                    }
                    if (IsConnected) Thread.Sleep(1000);//若连接正常，则每1秒一个周期
                    else Thread.Sleep(2000);
                    CycleCount++;//循环次数自增
                }
                catch (Exception ex)
                {
                    //SimpleLoger.Instance.Error(ex);
                }
            }
        }
        #endregion 线程相关
        #region 方法
        public ThreadPrinterMonitorV2d0()
        {
            PrinterIp = "192.168.3.99";
            PrinterPort = 9100;
            BasePrintSpeed = 2;
            IsBusy = false;
            IsConnected = false;
            IsPrinterReady = false;
            IsJzgNormal = true;//默认进纸盒是正常的（关闭状态）
            SocketConnectTimerOutMilliSecond = 1000;
            PulseCheckMRE = new ManualResetEvent(false);//初始化为无信号状态，阻塞
            DeviceType = "TM-U220";
        }
        /// <summary>
        /// 初始化变量
        /// </summary>
        public void Init()
        {
            BasePrintSpeed = 2;
            IsBusy = false;
            IsConnected = false;
            IsPrinterReady = false;
            IsJzgNormal = true;//默认进纸盒是正常的（关闭状态）
            SocketConnectTimerOutMilliSecond = 1000;
        }
        /// <summary>
        /// 套接字连接打印机，并发送初始化指令（使能asb）
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <param name="port">端口</param>
        /// <param name="timeOut">连接超时时间，毫秒</param>
        /// <returns>是否连接成功</returns>
        private bool ConnectToPrinterAndTryInit(string ip, int port,int timeOut=500)
        {
            bool result = false;
            try
            {
                PrinterTcpClient = new TcpClient();
                IAsyncResult iAR = PrinterTcpClient.BeginConnect(ip,port,null,null);
                //等待开门信号（如果接收到信号返回true，否则返回false）
                bool isConnected = iAR.AsyncWaitHandle.WaitOne(timeOut);
                if (!isConnected)
                {
                    PrinterTcpClient.Close();//关闭套接字
                    result=false;
                }                
                else 
                {
                    //如果连接成功，开始异步接收
                    StateObject sObject = new StateObject();
                    sObject.client = PrinterTcpClient;
                    NetworkStream netStream = PrinterTcpClient.GetStream();
                    if (netStream.CanRead)
                    {
                        netStream.BeginRead(sObject.buffer, 0, StateObject.BufferSize, new AsyncCallback(SocketAsyncReadCallBack), sObject);
                    }
                    //初始化打印机指令
                    byte[] bytesCommand = PrinterEscCommandConstantV2d0.init_printer();
                    //TmU220PrinterV2d0.SendBytesToPrinter(bytesCommand, PrinterTcpClient);
                    SendBytesToPrinter(bytesCommand, PrinterTcpClient);
                    //使能自动状态回复ASB,打印机收到此指令后，会立刻发回打印机状态四个字节
                    bytesCommand = PrinterEscCommandConstantV2d0.enableAsb();
                    //TmU220PrinterV2d0.SendBytesToPrinter(bytesCommand, PrinterTcpClient);
                    SendBytesToPrinter(bytesCommand, PrinterTcpClient);
                    result = true;
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 打印机SendBytesToPrinter指令的再封装
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="printerTcpClient"></param>
        /// <returns></returns>
        private bool SendBytesToPrinter(byte[] bytes, TcpClient printerTcpClient)
        {
            bool result = false;
            if (DeviceType == "TM-U220") result = TmU220PrinterV2d0.SendBytesToPrinter(bytes, printerTcpClient);
            else if (DeviceType == "XP-Q200") result = XpQ200PrinterV2d0.SendBytesToPrinter(bytes, printerTcpClient);
            return result;
        }
        /// <summary>
        /// 套接字异步网络流读取的回调函数
        /// </summary>
        /// <param name="iAsyncResult"></param>
        public void SocketAsyncReadCallBack(IAsyncResult iAsyncResult)
        {
            try
            {
                //从回传变量中得到状态对象
                StateObject sObject = iAsyncResult.AsyncState as StateObject;
                //主动断开时
                if ((sObject.client == null) || (!sObject.client.Connected)) return;
                NetworkStream currNetworkStream = sObject.client.GetStream();
                //得到读取的数据字节数
                int countOfBytesRead = currNetworkStream.EndRead(iAsyncResult);
                if (countOfBytesRead > 0)
                {
                    byte[] buffer = new byte[countOfBytesRead];
                    Array.Copy(sObject.buffer, 0, buffer, 0, countOfBytesRead);
                    foreach (byte data in buffer)
                    {
                        ReceiveSBuilder.Append((char)data);
                    }
                    //SimpleLoger.Instance.Info("已接收数据:" + ReceiveSBuilder.ToString());
                    //解析来自打印机的数据
                    ParseDataFromPrinter(ReceiveSBuilder);
                    //继续进行下一次的异步读取,并将tcpClient套接字的对象传递给回调函数
                    if(currNetworkStream.CanRead) currNetworkStream.BeginRead(sObject.buffer, 0, StateObject.BufferSize, new AsyncCallback(SocketAsyncReadCallBack), sObject);
                }
                else
                {
                    //被动断开时
                    currNetworkStream.Close();
                    sObject.client.Close();
                    currNetworkStream = null;
                    sObject = null;
                    IsConnected = false;
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            finally
            {
                //发出开门信号
                PulseCheckMRE.Set();
            }
        }

        /// <summary>
        /// 添加打印任务到数据队列
        /// </summary>
        /// <param name="printTask"></param>
        public void AddPrintTaskToDataQueue(PrintTaskV2d0 printTask)
        {
            PrintTaskQueue.Enqueue(printTask);
        }
        /// <summary>
        /// 从数据队列中取出一个打印任务
        /// </summary>
        /// <returns>如果未取出，则返回null</returns>
        private PrintTaskV2d0 GetPrintTaskFromDataQueue()
        {
            PrintTaskV2d0 printTask = null;
            try
            {
                bool result = PrintTaskQueue.TryDequeue(out printTask);
                int timeoutOfTask = SysCfgInfoSingletonV1d0.Instance.GetTimeoutOfTask();
                if (printTask != null)
                {
                    // 如果打印任务超时，就将该打印任务丢弃
                    if (((TimeSpan)(DateTime.Now - printTask.DataOfPrintTask.addtime)).TotalMinutes > timeoutOfTask)
                    {
                        return null;
                    }
                    else return printTask;
                }
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
                return null;
            }
            return printTask;
        }
        /// <summary>
        /// 解析打印机发回的数据，并更新打印机状态，发布打印机状态事件
        /// </summary>
        /// <param name="sBuilder"></param>
        private void ParseDataFromPrinter(StringBuilder sBuilder)
        {
            string stringBuffer = sBuilder.ToString();
            SimpleLoger.Instance.Info(HotchPotchV2d0.ConvertStringToHex(stringBuffer));
            int findedIndex = -1;
            //卷纸盖打开,且打印机正常
            int findedJzqOpen = -1;
            //卷纸盖关闭,且打印机正常
            int findedJzqClose = -1;
            int findedFourZero = -1;
            int findedNormal = -1;
            //双零，打印机正常，暂时不知道具体意义
            int findedDoubleZero = -1;
            //进纸盒正常,打印机正常
            int findedJzhOk = -1;
            //解析次数 ，一组数据最多解析5次就清空
            int parseCount = 0;
            try
            {
                while (stringBuffer.Length > 0&& parseCount<5)
                {
                    parseCount++;
                    //只要接收到数据，就认为已连接
                    IsConnected = true;
                    findedJzqClose = stringBuffer.IndexOf("\x14\x00\x00\x0F", 0);
                    if (findedJzqClose >= 0)
                    {
                        //未缺纸
                        IsPaperExhausted = false;
                        //打印机可用
                        IsPrinterReady = true;
                        IsJzgNormal = true;
                        sBuilder.Remove(findedJzqClose, 4);
                        stringBuffer = sBuilder.ToString();
                    }
                    findedJzqOpen = stringBuffer.IndexOf("\x1C\x00\x0C\x0F", 0);
                    if (findedJzqOpen >= 0)
                    {
                        //缺纸
                        IsPaperExhausted = true;
                        //打印机不可用
                        IsPrinterReady = false;
                        IsJzgNormal = false;
                        sBuilder.Remove(findedJzqOpen, 4);
                        stringBuffer = sBuilder.ToString();
                    }
                    findedFourZero = stringBuffer.IndexOf("\x00\x00\x00\x00", 0);
                    if (findedFourZero >= 0)
                    {
                        //未缺纸
                        IsPaperExhausted = false;
                        //打印机可用
                        IsPrinterReady = true;
                        IsJzgNormal = true;
                        sBuilder.Remove(findedFourZero, 4);
                        stringBuffer = sBuilder.ToString();
                    }
                    findedNormal = stringBuffer.IndexOf("\x00\x00\x00\x0F", 0);
                    if (findedNormal >= 0)
                    {
                        //未缺纸
                        IsPaperExhausted = false;
                        //打印机可用
                        IsPrinterReady = true;
                        IsJzgNormal = true;
                        sBuilder.Remove(findedNormal, 4);
                        stringBuffer = sBuilder.ToString();
                    }
                    findedDoubleZero = stringBuffer.IndexOf("\x00\x00", 0);
                    if (findedDoubleZero >= 0)
                    {
                        //未缺纸
                        IsPaperExhausted = false;
                        //打印机可用
                        IsPrinterReady = true;
                        IsJzgNormal = true;
                        sBuilder.Remove(findedDoubleZero, 2);
                        stringBuffer = sBuilder.ToString();
                    }
                    findedJzhOk = stringBuffer.IndexOf("\x00", 0);
                    if (findedJzhOk >= 0)
                    {
                        //未缺纸
                        IsPaperExhausted = false;
                        //打印机可用
                        IsPrinterReady = true;
                        IsJzgNormal = true;
                        sBuilder.Remove(findedJzhOk, 1);
                        stringBuffer = sBuilder.ToString();
                    }
                }
                //解析完成，清空字符缓冲
                sBuilder.Clear();
                //发布打印机状态事件
                if (PrinterStatusEvent != null)
                    PrinterStatusEvent(this, new PrinterStatusV2d0(IsConnected, IsPrinterReady, IsBusy, IsJzgNormal));
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 打印机心跳检测,是否已连接打印机,同时IsPrinterReady变量也被赋值
        /// </summary>
        /// <returns></returns>
        public bool PrinterPulseCheck()
        {
            try
            {
                PulseCheckMRE.Reset();
                bool sendSuccess = SendPrinterPulseCheckCommand(null);
                if (sendSuccess)
                {
                    //发送成功，检查是否收到开门信号
                    if (!PulseCheckMRE.WaitOne(3000, false))
                    {
                        //未收到开门信号 打印机离线
                        IsConnected = false;
                        IsPrinterReady = false;
                        IsBusy = false;
                        //关闭连接
                        PrinterTcpClient.Close();
                        //PrinterTcpClient = null;
                        //发布打印机状态事件 
                        if (PrinterStatusEvent != null)
                            PrinterStatusEvent(this, new PrinterStatusV2d0(IsConnected, IsPrinterReady, IsBusy, IsJzgNormal));
                    }                    
                }
                else
                {
                    //发送不成功 打印机离线
                    IsConnected = false;
                    IsPrinterReady = false;
                    IsBusy = false;
                    //关闭连接
                    PrinterTcpClient.Close();
                    //PrinterTcpClient = null;
                    //发布打印机状态事件 
                    if (PrinterStatusEvent != null)
                        PrinterStatusEvent(this, new PrinterStatusV2d0(IsConnected, IsPrinterReady, IsBusy, IsJzgNormal));
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return IsConnected;
        }

        /// <summary>
        /// 发送服务器心跳检测信号
        /// </summary>
        private bool SendPrinterPulseCheckCommand(object state)
        {
            bool result = false;
            try
            {
                //请求打印机发送进纸盒状态，作为心跳检测信号
                result = SendRequstPaperStatusCommand();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }

        /// <summary>
        /// 发送返回进纸器状态命令
        /// </summary>
        /// <returns></returns>
        private bool SendRequstPaperStatusCommand()
        {
            bool result = false;
            result = SendBytesToPrinter(PrinterEscCommandConstantV2d0.transferPaperSensorStatus(), PrinterTcpClient);
            return result;
        }

        /// <summary>
        /// 发送打印任务到打印机
        /// </summary>
        /// <param name="printTask"></param>
        /// <returns></returns>
        public bool SendPrintTaskToPrinter(PrintTaskV2d0 printTask)
        {
            bool result = false;
            IPrinter printer = PrinterFactory.GetPrinter(DeviceType, PrinterTcpClient, FontLibraryEncodingName);
            //TmU220PrinterV2d0 printer = new TmU220PrinterV2d0(PrinterTcpClient, FontLibraryEncodingName);
            //遍历打印任务项列表
            foreach (var item in printTask.PrintTaskItemList)
            {
                result = printer.SendPrintTaskItemToPrinter(item);
            }
            //发出关门信号
            PulseCheckMRE.Reset();
            //此处发送一个心跳检测指令。若打印机正常工作，则会立刻回应一个心跳
            //若接收到这个状态指令
            SendPrinterPulseCheckCommand(null);
            //切纸命令
            printer.SendBytes(PrinterEscCommandConstantV2d0.feedPaperCutAll());

            return result;
        }
        /// <summary>
        ///将打印数据的简繁体编码，转换为打印机的简繁体编码 
        ///简繁体处理，主打印数据是简体还是繁体，打印机是简体还是繁体
        /// </summary>
        /// <param name="printTask"></param>
        /// <param name="isTraditinalOfPrinter"></param>
        public void SimplifiedAndTraditionalProcess(ref PrintTaskV2d0 printTask, bool isTraditinalOfPrinter)
        {
            //繁体-繁体 无需转换
            if ((printTask.IsTraditional==1) && (isTraditinalOfPrinter)) return;
            //繁体-简体 需要转换
            if ((printTask.IsTraditional==1) && (!isTraditinalOfPrinter))
            {
                foreach (var item in printTask.PrintTaskItemList)
                {
                    item.Content = ChineseConverter.Convert(item.Content, ChineseConversionDirection.TraditionalToSimplified);
                }
                return;
            }
            //简体-繁体 需要转换
            if ((printTask.IsTraditional==0) && (isTraditinalOfPrinter))
            {
                foreach(var item in printTask.PrintTaskItemList)
                {
                    item.Content= ChineseConverter.Convert(item.Content, ChineseConversionDirection.SimplifiedToTraditional);
                }
                return;
            }
            //简体-简体 无需转换
            if ((printTask.IsTraditional==0) && (!isTraditinalOfPrinter))
            {

                return;
            }

        }
        #endregion 方法
    }
    /// <summary>
    /// 套接字异步读取的状态对象
    /// </summary>
    public class StateObject
    {
        public TcpClient client = null;
        public int totalBytesRead = 0;
        public const int BufferSize = 1024;
        public string readType = string.Empty;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder messageBuffer = new StringBuilder();
    }
}
